<?php
/**
 * 前台登录
 * User: Administrator
 * Date: 2019/5/24
 * Time: 11:48
 */

namespace PKApp\Member;

use PKApp\Member\Classes\MemberService;
use PKApp\Member\Classes\UserCtrl;
use PKFrame\DataHandler\Auth;
use PKFrame\DataHandler\JSON;
use PKFrame\DataHandler\MatchHelper;

class ApiLogin extends UserCtrl
{

    private $_loginType;

    public function Main()
    {
        $login = $this->_checkLoginOfObj();
        $pwd = $this->checkPostFieldIsEmpty('password', 'Empty_userPwd');
        $service_member = new MemberService();
        $res = $service_member->CheckLogin($login, $pwd, $this->_loginType);
        if (is_string($res)) {
            $this->writeLogByLogin(request()->post('login'), 'login_fail', language($res));
            $this->noticeByJson($res);
        }
        $this->writeLogByLogin(request()->post('login'), 'login_success');
        $key = md5($res['encrypt'] . TIMESTAMP);
        unset($res['encrypt']);
        $sign = Auth::Base64Encode(JSON::EnCode($res), true, $key, USER_ExpTime);
        fileHelper()->PutContents($this->pathOfUserLogin(), $key . '.log', $sign);
        $this->json(['userKey' => $key, 'userSign' => $sign]);
    }

    private function _checkLoginOfObj()
    {
        $login = $this->checkPostFieldIsEmpty('login', 'Empty_userName');
        if (MatchHelper::MatchFormatOfBool('mobile', $login)) {
            $this->_loginType = 'phone';
        } elseif (MatchHelper::MatchFormatOfBool('email', $login)) {
            $this->_loginType = 'email';
        } else {
            $this->_loginType = 'userName';
        }
        return $login;
    }

}